import face_recognition
from PIL import Image, ImageDraw, ImageFont

# face_landmarks(face_image, face_locations=None, model="large")
#
# 作用：检测图像中的人脸，并返回每张脸的特征点（如眼睛、鼻子、嘴巴等）。
# 参数：
# face_image：包含人脸的图像（NumPy 数组格式）。
# face_locations：已知的人脸位置的列表，如果未提供，该函数会自动检测人脸位置。
# model：用于检测特征点的模型，可以是 "large" 或 "small"。"large" 模型更准确但速度较慢，"small" 模型较快但精度稍低。


image_numpy = face_recognition.load_image_file('../img/two.jpg')

face_features = face_recognition.face_landmarks(image_numpy)


print(len(face_features))

# face_features为list, 且长度为图片中人脸的个数
# features = face_features[0]

pil_image = Image.fromarray(image_numpy)
draw = ImageDraw.Draw(pil_image)

# 特征点的像素大小
point_size = 2

# chin
# left_eyebrow
# right_eyebrow
# nose_bridge
# nose_tip
# left_eye
# right_eye
# top_lip
# bottom_lip

# draw.polygon(features["top_lip"], fill="white")
# draw.polygon(features["bottom_lip"], fill="red")


for features in face_features:
    for feature in features.keys():
        print(feature)
        if feature != "left_eye":
            for coord in features[feature]:
                draw.rectangle([coord[0] - point_size // 2, coord[1] - point_size // 2, coord[0] + point_size // 2, coord[1] + point_size // 2], fill="white")
        else:
            # 显示左眼特征点的序号
            index = 0
            for coord in features[feature]:
                text = str(index + 1)
                font = ImageFont.truetype('arial.ttf', 8)
                # 文本的位置
                draw.rectangle([coord[0] - point_size // 2, coord[1] - point_size // 2, coord[0] + point_size // 2, coord[1] + point_size // 2], fill="white")
                if index == 0 or index == 1:
                    draw.text((coord[0] - 2, coord[1] - 10), text, fill="red", font=font)
                if index == 2:
                    draw.text((coord[0], coord[1] - 10), text, fill="red", font=font)
                if index == 3:
                    draw.text((coord[0] + 1, coord[1]), text, fill="red", font=font)
                if index == 4 or index == 5:
                    draw.text((coord[0], coord[1] + 1), text, fill="red", font=font)
                index += 1
        # draw.line(features[feature], fill="white", width=4)


pil_image.show()





